﻿using System.Data;
using System.Drawing;
using System;
using System.Collections.Generic;

namespace Home.Haushalt.Lib.Element
{
    /// <summary>
    /// 
    /// </summary>
    [ElementExtension("Element", 0)]
    public class Posten : ElementBase
    {
        #region CONSTANTS
        public new static readonly Type ElementType = typeof(Posten);

        /// <summary></summary>
        public class Fields
        {
            public const string Id = ELEMENTPROPERTY_ID;
            public const string Label = ELEMENTPROPERTY_LABEL;
            public const string Description = ELEMENTPROPERTY_NOTE;
            public const string Name = "e";
            public const string DateFrom = "z";
            public const string DateTo = "t";
            public const string SerieId = "w";
            public const string Summe = "o";
            public const string DateDay = "p";
            public const string Basement = "b";
            public const string OwnId = "u";
            public const string OpponentId = "f";
            public const string OpponentExt1Id = "f1";
            public const string OpponentExt2Id = "f2";
            public const string ParentPostenId = "y";
            public const string GroupId = "h";
            public const string PostengruppeId = "v";
            public const string SaldotypeId = "g";
            public const string Turnus = "d";
            public const string TurnusPeriode = "a";

            public const string UnboundDateSum = "datesum";
            public const string UnboundDateCount = "datecount";
            public const string UnboundAverage = "average";
            public const string UnboundAverageTag = "averagetag";
            public const string UnboundLengthMonth = "lengthmonth";
            public const string UnboundLengthTag = "lengthtag";
        }
        #endregion CONSTANTS

        /// <summary></summary>
        public override string PropertyFormCaption { get { return (Row != null) ? Row[Fields.Name].ToString() : ""; } }

        #region APEARANCES

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override Color GetRowForeColor()
        {
            Color foreColor = base.GetRowForeColor();

            if (CheckColumnsInRow(Fields.DateFrom, Fields.DateTo, Fields.Basement))
            {
                if (Row[Fields.DateFrom].ToDateTime() <= DateTime.Today)
                    foreColor = DAO.Settings.Selected.RowStateColorActive;
                if (Row[Fields.DateTo] != DBNull.Value && Row[Fields.DateTo].ToDateTime() < DateTime.Today)
                    foreColor = DAO.Settings.Selected.RowStateColorOld;

                if (Row[Fields.DateFrom].ToDateTime() > DateTime.Today)
                    foreColor = DAO.Settings.Selected.RowStateColorFuture;
                if (Row[Fields.Basement].ToBool(false))
                    foreColor = DAO.Settings.Selected.RowStateColorBasement;
            }
            return foreColor;
        }

        #endregion APEARANCES

        /// <summary>
        /// 
        /// </summary>
        public Posten() : base() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentDataRow"></param>
        public Posten(DataRow parentDataRow) : base(parentDataRow) { }

        #region OVERRIDES

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override Dictionary<string, object> CalculateUnboundFields()
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            if (CheckColumnsInRow(Fields.Id))
            {
                //Summe
                double sum = 0;
                DataRow[] foundRows = DAO.GetSubRows(Date.ElementType, Date.Fields.PostenId, ID);

                //if (ID.Equals(1180))
                //{
                //}

                int ownFactor = Row[Fields.OwnId].ToBool(false) ? -1 : 1;
                foreach (DataRow row in foundRows)
                {
                    if (!row[Date.Fields.Active].ToBool(false))
                    {
                        double value = row[Date.Fields.Summe].ToDouble() * row[Date.Fields.SaldotypId].ToInt();
                        sum += (value * ownFactor);
                    }
                }

                //Mittelwert Monat
                long endDateTick = (Row[Fields.DateTo] != DBNull.Value && Row[Fields.DateTo].ToDateTime() < DateTime.Now) ? Row[Fields.DateTo].ToDateTime().Ticks : DateTime.Now.Ticks;

                TimeSpan ts = new TimeSpan(endDateTick - Row[Fields.DateFrom].ToDateTime().Ticks);

                double lengthtag = ts.TotalDays > 0 ? ts.TotalDays : 0;
                double lengthmonth = (lengthtag < 30) ? 0 : lengthtag * 12 / 365;

                double average = (lengthmonth > 0) ? sum / lengthmonth : sum;
                double averagetag = (lengthtag > 0) ? sum / lengthtag : sum;

                result.Add(Fields.UnboundDateSum, sum);
                result.Add(Fields.UnboundDateCount, foundRows.Length);
                result.Add(Fields.UnboundAverage, average);
                result.Add(Fields.UnboundAverageTag, averagetag);
                result.Add(Fields.UnboundLengthMonth, Math.Round(lengthmonth));
                result.Add(Fields.UnboundLengthTag, Math.Round(lengthtag));
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ElementBase New()
        {
            base.New();

            Row[Fields.DateFrom] = DateTime.Now;

            if (ParentElement is Opponent)
            {
                Row[Fields.OpponentId] = ParentElement.Row[Opponent.Fields.Id];
            }
            else if (ParentElement is Posten)
            {
                Row[Fields.PostengruppeId] = ParentElement.Row[Posten.Fields.PostengruppeId];
                Row[Fields.GroupId] = ParentElement.Row[Posten.Fields.GroupId];
                Row[Fields.OpponentId] = ParentElement.Row[Posten.Fields.OpponentId];
            }

            return this;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override List<string> InputValidate()
        {
            List<string> result = new List<string>();

            if (BindingRow[Fields.Name].ToString().Trim().Length == 0) result.Add(GetInputValidateMessage(this.GetType(), Fields.Name, "missing"));
            if (BindingRow[Fields.OpponentId].ToInt() == -1) result.Add(GetInputValidateMessage(this.GetType(), Fields.OpponentId, "missing"));
            if (BindingRow[Fields.GroupId].ToInt() == -1) result.Add(GetInputValidateMessage(this.GetType(), Fields.GroupId, "missing"));

            return result;
        }

        #endregion OVERRIDES


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static int GetNextSerieId()
        {
            int serieId = 0;

            DataRow[] rows = DAO.Tables[Posten.ElementType].Select("", Posten.Fields.SerieId + " desc");

            if (rows.Length > 0)
            {
                serieId = rows[0][Posten.Fields.SerieId].ToInt() + 1;
            }

            return serieId;
        }

    }
}
